//
//  MusicViewController.m
//  AnimationRecommend
//
//  Created by ljm on 2017/2/14.
//  Copyright © 2017年 ljm. All rights reserved.
//

#import "MusicViewController.h"
#import "releaseDynamicViewController.h"
#import "MomentsViewModel.h"
#import "MomentsTableViewCell.h"
#import "UIScrollView+EmptyDataSet.h"


@interface MusicViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,cellBtnClickedDelegate> {
    
    NSMutableArray *_moentsVMArr;
    NSMutableArray *_objectArr;
}

@property(nonatomic,strong) UITableView *tableView;
@property (nonatomic, getter=isLoading) BOOL loading;


@end

@implementation MusicViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setupData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    _moentsVMArr = [NSMutableArray new];
    [self setupData];
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)setLoading:(BOOL)loading
{
//    NSLog(@"loading == %d ,,,,,,-----------,,,,,self.isLoading = %d",loading,self.isLoading);
    if (self.isLoading == loading) {
        return;
    }
    _loading = loading;
    [self.tableView reloadEmptyDataSet];
    [self selMomentsViewModel];
}


- (void)setupData {
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf selMomentsViewModel];
    }];
    [self.tableView.mj_header beginRefreshing];
}


- (void)selMomentsViewModel {

    __weak typeof(self) weakSelf = self;
    AVQuery *query = [AVQuery queryWithClassName:@"Product"];
    
    [query orderByDescending:@"createdAt"];
    // owner 为 Pointer，指向 _User 表
    [query includeKey:@"owner"];
    
    // image 为 File
    for (int i = 0; i < 10; i++) {
        [query includeKey:[NSString stringWithFormat:@"image_%d",i]];
    }
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            [_moentsVMArr removeAllObjects];
//            _objectArr = [NSMutableArray arrayWithArray:objects];
            for (int i = 0; i < objects.count; i++) {
                AVObject *oj = objects[i];
                //NSLog(@"================\n\n有数据了嘛……%@",oj);
                MomentsViewModel *moentsVM = [[MomentsViewModel alloc] init];
                //NSLog(@"\n--- tableVIew 加载数据了 ---- %@-------\n",oj);
                
                NSString *text = [oj objectForKey:@"text"];
                
                NSDate *date = [oj objectForKey:@"createdAt"];
                NSDateFormatter* forMatter = [NSDateFormatter new];
                [forMatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSString *createdAt = [forMatter stringFromDate:date];
                
                AVUser *owner =[oj objectForKey:@"owner"];
                
                NSString *userName = [owner objectForKey:@"nikeName"];
                //NSLog(@"====================\n昵称：；%@",userName);
                AVFile *file = [owner objectForKey:@"iconImage"];
                NSString *iconImage = file.url;
                if (iconImage == nil) iconImage = @"";
                NSMutableArray *photos = [NSMutableArray new];
                NSMutableArray  *smallPhotos = [NSMutableArray new];
                for (int i = 0; i < 10; i++) {
                    AVFile *file = [oj objectForKey:[NSString stringWithFormat:@"image_%d",i]];
                    //NSLog(@"========\n\n\n得到的图片文件：…%@\n\n============\n",file);
                    if (file != NULL) {
                        //获得缩略图
                        AVFile *smallFile = [AVFile fileWithURL:file.url];
                        NSString *url = [smallFile getThumbnailURLWithScaleToFit:YES width:100 height:100];
                        [smallPhotos addObject:url];
                        //NSLog(@"\n------能得到缩略图的URL嘛\n------%@",url);
                        [photos addObject:file.url];
                        //NSLog(@"%@\n",file.url);
                    }
                }
                NSArray *allPhotos = @[smallPhotos,photos];
                NSLog(@"=====\n\n\n缩略图数组个数：%ld ==  原图::%ld",smallPhotos.count,photos.count);
                if (userName == nil) userName = @"获取用户名失败";
                NSDictionary *dic = @{@"text":text,@"userName":userName,@"createdAt":createdAt,@"iconImage":iconImage,@"photos":allPhotos};
                Moments *momentS = [Moments initWithDic:dic];
                //NSLog(@"%@\n,%@\n,%@\n",momentS.userName,momentS.createdAt,momentS.photos);
                moentsVM.moment = momentS;
                [_moentsVMArr addObject:moentsVM];
            }

            [weakSelf.tableView reloadData];
            [weakSelf.tableView.mj_header endRefreshing];
                weakSelf.loading = NO;
            
        }else {
    
            [weakSelf.tableView.mj_header endRefreshing];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    weakSelf.loading = NO;
                });

        }
    }];
}

- (void)setupUI {
    UIImage *image = [UIImage imageNamed:@"info_renz"];
    image = [image  imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *releaseBtn = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(releaseDynamic)];
    self.navigationItem.rightBarButtonItem = releaseBtn;
    
    [self.view addSubview:self.tableView];
}

#pragma mark - 发布动态

- (void) releaseDynamic {
    
    [self.navigationController pushViewController:[[releaseDynamicViewController alloc] init] animated:YES];
}

#pragma mark - cellBtnDelegate

- (void)cellBtnClick:(UIButton *)btn {
//    MomentsTableViewCell *cell = (MomentsTableViewCell *)[[btn superview] superview];
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    //NSLog(@"%ld",indexPath.section);
    
//    if (btn.tag == 1001) {
//        NSLog(@"点赞");
//        NSString *userName = vm.moment.userName;
//        AVObject *likes = [AVObject objectWithClassName:@"Tag"];
//        [likes setObject:userName forKey:@"CommentAndLikes"];
//        
//        AVRelation *relation = [object relationForKey:@"tag"];// 新建一个 AVRelation
//        [relation addObject:likes];
//        
//        [object saveInBackground];// 保存到云端
   // }
    //if (btn.tag == 1002) NSLog(@"评论");

}

#pragma mark - tableViewDelegate And DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _moentsVMArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MomentsTableViewCell *cell = [MomentsTableViewCell loadTableViewCellWithTableView:tableView];
    cell.momentVM = _moentsVMArr[indexPath.section];
    cell.delegate = self;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MomentsViewModel *model = _moentsVMArr[indexPath.section];
    return model.cellHeight;
}

//section底部视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor clearColor];
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return bodyCellMargin;
}

#pragma mark - DZNEmptyDataSetSource Methods
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = nil;
    if (self.isLoading) text = @"正在重新加载.....";
    else                text = @"加载动态信息失败";
    UIFont *font = [UIFont boldSystemFontOfSize:17.0];
    UIColor *textColor = [UIColor cz_colorWithHex:0x25282b];
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];

}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = nil;
    if (self.isLoading) text = @"请耐心等待";
    else                text = @"服务器无数据或者网络不好哦";
    UIFont *font = [UIFont boldSystemFontOfSize:14.5];
    UIColor *textColor = [UIColor cz_colorWithHex:0x7b8994];
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];

}

-(UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIColor cz_colorWithHex:0xf0f3f5];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    if (self.isLoading)
        return [UIImage imageNamed:@"loading_imgBlue_78x78"];
    else
        return [UIImage imageNamed:@"placeholder_dropbox"];
}

- (BOOL)emptyDataSetShouldAnimateImageView:(UIScrollView *)scrollView
{
    return self.isLoading;
}

- (CAAnimation *)imageAnimationForEmptyDataSet:(UIScrollView *)scrollView
{
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D: CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 1.0) ];
    animation.duration = 0.25;
    animation.cumulative = YES;
    animation.repeatCount = MAXFLOAT;
    
    return animation;
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state {
    
    NSString *text = @"重新加载";
    if (self.isLoading)     text = @"";
    
    UIFont *font = [UIFont boldSystemFontOfSize:14.5];
    UIColor *textColor = [UIColor cz_colorWithHex:(state == UIControlStateNormal) ? 0x007ee5 : 0x48a1ea];
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    
    if (font) [attributes setObject:font forKey:NSFontAttributeName];
    if (textColor) [attributes setObject:textColor forKey:NSForegroundColorAttributeName];
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];

}

- (void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button {
    self.loading = YES;
    
    
}

#pragma mark - getters
- (UITableView *)tableView {
    
    CGFloat tableViewH = kheight - 49;
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kwidth, tableViewH) style:UITableViewStylePlain];
        //防止tableView 被 tabbar 挡住
        _tableView.contentInset = UIEdgeInsetsMake(0.f, 0.f, CGRectGetHeight(self.tabBarController.tabBar.frame), 0.f);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = iCodeTableviewBgColor;
    }
    return _tableView;
}


@end
